package com.david.core.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/*
使用示例：
ArrayList<FlowLayout.FlowData> flowItems = new ArrayList();
        for (int i = 0;i<16;++i) {
            FlowLayout.FlowData itemFlow = new FlowLayout.FlowData();
            itemFlow.content = "hahha" + i;
            flowItems.add(itemFlow);

            Log.e("flow", "added item is " + "hahha" + i);

        }
        flow_view.setOnFlowItemClickListener(new OnFlowItemClickListener(){
            @Override
            public void onFlowItemClick(FlowLayout.FlowData data) {
                if (data != null) {
                    Log.e("flow", "clicked item is " + data.content)
                }
            }
        });
        flow_view.setItems(flowItems, R.layout.item_flow);

 */

//流式布局，自动换行View
public class FlowLayout extends ViewGroup implements View.OnClickListener {

    private int itemSpace = 10;

    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private ArrayList<ArrayList<View>> lineViews = new ArrayList<>();//每一行View
    private ArrayList<Integer> lineHeights = new ArrayList<>();

    /**
     * 测量子View及自身宽高
     * */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        lineViews.clear();
        lineHeights.clear();

        int selfWidth = MeasureSpec.getSize(widthMeasureSpec);
        int selfHeight = MeasureSpec.getSize(heightMeasureSpec);

        int lineWidth = getPaddingLeft();//每一行宽度
        int allLineHeight = getPaddingTop();//总item高度

        int maxLineWidth= getPaddingLeft();//最大行宽

        int maxLineHeight= 0;//每一行最大高度

        ArrayList<View> lineView  = new ArrayList<>();
        for (int i = 0; i < getChildCount(); ++i) {
            LayoutParams params = getChildAt(i).getLayoutParams();
            int widthSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft(), params.width);
            int heightSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft(), params.height);

            View child = getChildAt(i);
            child.measure(widthSpec, heightSpec);//子view测量

            if (lineWidth + getPaddingRight() + child.getMeasuredWidth() > selfWidth) {
                maxLineWidth = Math.max(maxLineWidth, lineWidth);
                allLineHeight += itemSpace + maxLineHeight;//总高度添加上一行最大行高

                maxLineHeight = child.getMeasuredHeight();//重置最大item高度

                lineWidth = getPaddingLeft();//重置行宽

                lineViews.add(lineView);
                lineHeights.add(maxLineHeight);
                lineView = new ArrayList<>();
            }
            lineWidth += child.getMeasuredWidth() + itemSpace;
            lineView.add(child);
            maxLineHeight = Math.max(maxLineHeight, child.getMeasuredHeight());
        }
        allLineHeight += itemSpace + maxLineHeight;

        lineViews.add(lineView);


        int width = MeasureSpec.EXACTLY == MeasureSpec.getMode(widthMeasureSpec)?selfWidth: maxLineWidth + getPaddingRight();
        int height = MeasureSpec.EXACTLY == MeasureSpec.getMode(heightMeasureSpec)?selfHeight: allLineHeight + getPaddingBottom();
        setMeasuredDimension(width, height);
    }

    public void setItemSpace(int itemSpace) {
        this.itemSpace = itemSpace;
        if (getChildCount()>0) {//已经有item了刷新布局
            invalidate();
        }
    }

    /**
     * 对子view布局
     * */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();

        int childWidth = paddingLeft;
        int childHeight = paddingTop;

        int childMaxHeight = 0;

        for (ArrayList<View> item:lineViews) {
            for (View childItem:item) {
                childMaxHeight = Math.max(childMaxHeight, childItem.getMeasuredHeight());
                childItem.layout(childWidth, childHeight, childWidth + childItem.getMeasuredWidth(), childHeight+childItem.getMeasuredHeight());

                childWidth += itemSpace + childItem.getMeasuredWidth();
            }
            childHeight += itemSpace + childMaxHeight;
            childWidth = paddingLeft;
        }
    }


    /**
     * 设置流式布局item项
     * @param items 数据列表
     * @param textViewLayout textView布局layoutId
     */
    public void setItems(List<FlowData> items, int textViewLayout) {
        removeAllViews();
        for (int i = 0; i <items.size(); ++i) {
            TextView itemView = (TextView) LayoutInflater.from(getContext()).inflate(textViewLayout, this, false);
            itemView.setText(items.get(i).content);
            itemView.setTag(items.get(i));
            itemView.setOnClickListener(this);
            addView(itemView);
        }
        invalidate();
    }

    @Override
    public void onClick(View v) {
        if (onFlowItemClickListener != null) {
            onFlowItemClickListener.onFlowItemClick((FlowData) v.getTag());
        }
    }

    private OnFlowItemClickListener onFlowItemClickListener;

    public void setOnFlowItemClickListener(OnFlowItemClickListener onFlowItemClickListener) {
        this.onFlowItemClickListener = onFlowItemClickListener;
    }

    public interface OnFlowItemClickListener{
        void onFlowItemClick(FlowData data);
    }

    public static class FlowData{
        public String content;

        /**
         * 继承时重写，用于点击之后获取点击item的id
         * @return 被点击item的id
         */
        public String getId(){
            return "";
        }
    }
}
